<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- localStorage 例子 -->
    <div>
        请输入姓名：
        <input type="text" id="my-name">
        <button onclick="save()">保存</button>
        <button onclick="get()">获取姓名</button>
    </div>

    <!-- sessionStorage 例子 -->
    <div>
        <p id="ganfan_id"> 你已经干了0碗饭！！！</p>
        <button onclick="ganfan()">我能去你家干一碗饭吗？</button>
    </div>

    <script>
        function save() {
            var myName = document.getElementById("my-name").value;
            if (typeof(Storage) !== "undefined") {
                // localStorage 特点：没有过期时间（without any expiration date）,浏览器关闭，数据也不会删除
                // 键值对 key/value
                localStorage.name = myName;
                alert("保存成功");
            }
        }

        function get() {
            if (typeof(Storage) !== "undefined") {
                var myName = localStorage.name;
                alert(myName);
            }
        }

        function ganfan() {
            if (typeof(Storage) !== "undefined") {
                // sessionStorage 特点：只有一个会话（session）时间，关闭浏览器之后数据被删除
                if (sessionStorage.count) {
                    sessionStorage.count++;
                } else {
                    sessionStorage.count = 1;
                }
                document.getElementById("ganfan_id").innerHTML = "你已经干了" + sessionStorage.count + "碗饭！！！";
            }
        }
    </script>


</body>

</html>